

#include "iot_server.h"
#if defined(LOG_TAG)
#undef LOG_TAG 
#define LOG_TAG    "recv_mob_thread"
#else 
#define LOG_TAG    "recv_mob_thread"
#endif


char mob_str[4][20]= {0}; //定义解析字符串的二维数组		


static void dev_op(int dev, int on)  //static  文件内可见
{
	if (dev == 1) {  //设备1
		if (on == 1) //开
			log_d("led2 green on");
		else //关
			log_d("led2 green off");
		
	}
	if (dev == 2) {  //设备2
		if (on == 1)
			log_d("led2 orange on");
		else
			log_d("led2 orange off");
	}

	//调用设备的驱动程序

	
}



void* recv_mob_thread(void *arg)
{
	int ret;
	char buf[SIZE];
	int newfd = *((int *)arg);
	int on = -1;
	int dev = 0;
	while (1) {
		bzero(buf, SIZE);
		ret = recv(newfd, buf, sizeof(buf), 0); //类似read  阻塞
		if (ret < 0)
			log_e("recv fail");


		log_e("[%d]>收到手机端发送的字符串:%s", __LINE__, buf);

		//将socket中接收数据缓冲区解析
		bzero(mob_str[0], strlen(mob_str[0])); 
		bzero(mob_str[1], strlen(mob_str[1])); 
		bzero(mob_str[2], strlen(mob_str[2])); 
		bzero(mob_str[3], strlen(mob_str[3])); 
		sscanf(buf, "%s%s%s%s", mob_str[0], mob_str[1],mob_str[2], mob_str[3]);
		
		//登录处理
		if ( (strncmp(mob_str[1], SER_REQ_LOGIN_HEAD, strlen(mob_str[1]) )== 0) &&
			(strlen(mob_str[1]) > 0)){
			log_e("[%d]>收到手机端登录请求", __LINE__);
			log_e("mob_str[2]=%s", mob_str[2]);
			log_e("mob_str[3]=%s", mob_str[3]);

			ret = do_login(mob_str[2], mob_str[3]);
			log_e("ret=%d", ret);
			if (ret == 9)
				send(newfd, SER_ACK_NO, strlen(SER_ACK_NO), 0);
			else if (ret == 1)
				send(newfd, SER_ACK_YES, strlen(SER_ACK_YES), 0);
			else 
				send(newfd, SER_ACK_NO, strlen(SER_ACK_NO), 0);

		}else if(strncmp(mob_str[0],SER_REQ_CMD_HEAD,strlen(mob_str[0])) == 0) {
			// "control mac led2_green|orange on|off"
			//控制请求
			log_e("[%d]>req head:%s\n devmac:%s\nhwName:%s\ncmd:%s",__LINE__,mob_str[0],mob_str[1],mob_str[2],mob_str[3]);
			log_e("[%d]>接收到移动端的控制请求.", __LINE__);
			log_e("[%d]>目标设备的MAC地址:%s", __LINE__, mob_str[1]);
			log_e("[%d]>指令:%s %s\n", __LINE__, mob_str[2], mob_str[3]);	
			if (strncmp(mob_str[2], "led2_green", sizeof("led2_green")) == 0) dev=1;
			if (strncmp(mob_str[2], "led2_orange", sizeof("led2_orange")) == 0) dev=2; //表示不同的设备
			if (strncmp(mob_str[3], "on", 2) == 0) 	on=1;
			if (strncmp(mob_str[3], "off", 3) == 0) on=0;
			dev_op(dev, on); //调用控制设备的函数
		}
		if (ret == 0) {
			log_e("client fd=%d offline", newfd);
			break;
		}

	}
	return NULL;

}

